import { ref, Ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
import type { MaybeElementRef } from '@vueuse/core'

export const useLazyData = <T = any>(target: MaybeElementRef, apiFn: any) => {
  const result: Ref<T[]> = ref([])
  const { stop } = useIntersectionObserver(
    target,
    async ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        const response = await apiFn()
        result.value.push(...response.result)
      }
    }
  )
  return { result }
}
